package com.miku.blog.handler;

import com.miku.blog.domain.pojo.ResponseResult;
import com.miku.blog.eume.HttpStatusEnum;
import com.miku.blog.exception.SystemException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * @author shkstart
 * @create ${}YEAR-05-25 0:38
 */
@Slf4j
@ResponseBody
@ControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(SystemException.class)
    public ResponseResult handlerSystemException(SystemException systemException) {
        log.error(">>>>> 出现自定义异常 <<<<<");
        log.error(systemException.getMessage());
        log.error(">>>>> END <<<<<" + System.lineSeparator());
        return new ResponseResult().setCode(systemException.getCode())
                .setMessage(systemException.getMessage());
    }

    @ExceptionHandler(AuthenticationException.class)
    public ResponseResult handlerAccessDeniedException(AuthenticationException authenticationException) {
        log.error(">>>>> 身份认证失败 <<<<<");
        log.error(authenticationException.getMessage());
        log.error(">>>>> END <<<<<" + System.lineSeparator());
        return new ResponseResult(HttpStatusEnum.UNAUTHORIZED).setMessage(authenticationException.getMessage());
    }


    @ExceptionHandler(AccessDeniedException.class)
    public ResponseResult handlerAccessDeniedException(AccessDeniedException accessDeniedException) {
        log.error(">>>>> 访问权限不足 <<<<<");
        log.error(accessDeniedException.getMessage());
        log.error(">>>>> END <<<<<" + System.lineSeparator());
        return new ResponseResult(HttpStatusEnum.FORBIDDEN);
    }

    @Order
    @ExceptionHandler(Exception.class)
    public ResponseResult handlerException(Exception exception){
        log.error(">>>>> 系统出现异常 <<<<<", exception);
        log.error(">>>>> END <<<<<" + System.lineSeparator());
        return ResponseResult.error().setMessage(exception.getMessage());
    }

}
